package com.platform.dahuatech.icc.config;

import cn.hutool.core.codec.Base64;
import com.dahuatech.icc.exception.ClientException;
import com.dahuatech.icc.oauth.http.DefaultClient;
import com.dahuatech.icc.oauth.http.IClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.X509EncodedKeySpec;

/**
 * @author 贾伟焘
 * @version 1.0
 * @Classname IccClient
 * @Description TODO
 * @Date 2022/5/18 14:24
 */
@Configuration
public class IccClientConfig {
    @Bean
    public IClient iccDefaultClient() throws ClientException {
        return new DefaultClient();
    }

    /**
     * RSA公钥加密
     *
     * @param password 待加密的密码
     * @param publicKey 公钥
     * @return 密文
     */
    public static String encryptRSA(String password, String publicKey) {
        // base64编码的公钥
        try {
            byte[] decoded = Base64.decode(publicKey);
            RSAPublicKey pubKey =
                    (RSAPublicKey)
                            KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
            // RSA加密
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, pubKey);
            //**此处Base64编码，开发者可以使用自己的库**
            String outStr = Base64.encode(cipher.doFinal(password.getBytes("UTF-8")));
            return outStr;
        } catch (Exception e) {

        }
        return null;
    }

    /**
     * apipost 获取加密密码
     * @param args
     */
    public static void main(String[] args) {
        System.err.println(encryptRSA("dahua@2022!", "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCWbFic8iGzbYHCRkvNmDShwkTNjF60tN9fJhTxQRyT+LJbOI9/LlnNgEvKW8cQjr3bVX/pzTIni79ndzSmRDJHNKLrAmd5/KIq6u6uZB0PcuVRY7sq2allH8c1wTvtD6NzVWJwaF9np+6kp5KlZ7CjT3EIFwFZDSnsjY0fuw+fNwIDAQAB"));
    }
}
